package com.weipt;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author peter.wei 2020/08/31 16:15
 * @version 1.0
 * @company CBI
 * @description <br>peter.wei 2020/08/31 16:15 提供单例，不允许new，饿汉模式，程序启动就创建，浪费
 **/
public class Single3 {

    public static volatile Single3 SINGLE_3;  //防止指令重排

    private Single3(){
        synchronized (Single3.class){
            if(SINGLE_3 != null){
                throw new RuntimeException();
            }
        }
    }
    
    //使用类直接调用方法获取实例
    //synchronized防止线程不安全  dcl模式
    public static Single3 getSingle3(){
        if(SINGLE_3 == null){
            synchronized (Single3.class){
                if(SINGLE_3 == null){
                    //此处可能由于指令重排问题，导致小几率出现对象不一致
                    SINGLE_3 = new Single3();
                }
            }
        }
        return SINGLE_3;
    }
}

class TestSingle{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //Constructor<Single3> declaredConstructor = Single3.class.getDeclaredConstructor(null);
        Constructor<Single3> declaredConstructor = Single3.class.getDeclaredConstructor(String.class, int.class);
        //Annotation[] declaredAnnotations = Single3.class.getDeclaredAnnotations();
        declaredConstructor.setAccessible(true);
        Single3 single3 = declaredConstructor.newInstance();
        Field[] fields = Single3.class.getFields();
        System.out.println(Single3.getSingle3());
        System.out.println(single3);
    }
}